package tmp;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.core.Ordered;

@Aspect
public class RetryAdvice implements Ordered {

	private static final int DEFAULT_MAX_RETRIES = 1;
	private int maxRetries = DEFAULT_MAX_RETRIES;

	public static RetryAdvice aspectOf() {
		return new RetryAdvice();
	}

	@Pointcut("@annotation(tmp.Retryable)")
	public void retryableOperation() {
	}

	@Around("retryableOperation()")
	public Object doOperation(ProceedingJoinPoint pjp) throws Throwable {
		System.out.println("retrying000");

		int numAttempts = 0;
		Exception lastErr = null;
		do {
			numAttempts++;
			try {
				Object retVal = pjp.proceed();
				System.out.println("1111retrying");
				return retVal;
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("retrying");
				lastErr = e;
			}
		} while (numAttempts < maxRetries);

		throw lastErr;
	}

	public int getOrder() {
		return 0;
	}

	public void setMaxRetries(int maxRetries) {
		this.maxRetries = maxRetries;
	}
}
